package com.blkj.framework.aspectj;

import com.blkj.common.annotation.HasPermission;
import com.blkj.common.exception.base.BaseException;
import com.blkj.common.exception.user.UserNoAuthException;
import com.blkj.common.utils.ServletUtils;
import com.blkj.common.utils.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 北浪 2021/11/22
 */
@Aspect
@Component
public class PermissionAspectj {

    @Pointcut("@annotation(com.blkj.common.annotation.HasPermission)")
    public void pointCut(){

    }

    @Before("pointCut()")
    public void around(JoinPoint point){
        MethodSignature signature = (MethodSignature) point.getSignature();
        HasPermission hasPermission = signature.getMethod().getAnnotation(HasPermission.class);
        String hasRole = hasPermission.value();

        HttpServletRequest request = ServletUtils.currentServlet();
        String role = (String) request.getSession().getAttribute("role");

        if (StringUtils.isEmpty(hasRole)){
            throw new BaseException("500","未设置权限标识，请联系管理员");
        }
        if (!hasRole.equals(role)){
            throw new UserNoAuthException();
        }
    }

}
